package com.itsu.controller;

import com.itsu.compoment.socket.Message;
import com.itsu.service.MessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 苏犇
 * @create time 2019/12/5 23:08
 */
@Controller
public class MyController {

    @Resource
    private MessageService messageService;

    @PostMapping("/login.do")
    public String login(String userName, String password, HttpServletRequest request, Model model) {
        if (StringUtils.isNotBlank(userName) && StringUtils.isNotBlank(password)) {
            request.getSession().setAttribute("userId", userName);
            return "redirect:/toIndex";
        } else {
            model.addAttribute("errorMsg", "login fail");
            return "login";
        }
    }

    @GetMapping("/toIndex")
    public ModelAndView toIndex() {
        return new ModelAndView("index");
    }


    @PostMapping(value = "/submsg.do", produces = "application/json")
    @ResponseBody
    public Map subMsg(@RequestBody Message message) {
        Map map = new HashMap();
        try {
            message.setCreateTime(new Date());
            message.setStat("N");
//            messageService.saveOne(message);
            messageService.sendToQueue(message);
            map.put("result", true);
        } catch (Exception e) {
            map.put("result", false);
            map.put("msg", e.getMessage());

        }

        return map;
    }

}
